package com.hliushi.learn.web;

import com.hliushi.learn.config.MicroServiceUrl;
import com.hliushi.learn.utils.PropertiesUtils;
import com.hliushi.learn.utils.SpringApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author llhuang10
 * @date 2021/8/22 15:06
 */
@Slf4j
@RestController
@RequestMapping("/curd")
public class CURDResource {


    @GetMapping("/info")
    public String info(HttpServletResponse response) {
        /**
         * 解决跨域的第一种方式, 响应头添加Header允许访问
         */
        response.addHeader("Access-Control-Allow-Origin", "*");
        return new Date().toString();
    }

    @GetMapping("/prop-util")
    public String propUtil() {
        MicroServiceUrl microServiceUrl = PropertiesUtils.getMicroServiceUrl();
        StringRedisTemplate stringRedisTemplate = PropertiesUtils.getRedisTemplate();
        Object key = stringRedisTemplate.opsForValue().get("key");
        log.info("redisTemplate.opsForValue().get(key) : {}", key);
        log.info("microServiceUrl: {}", microServiceUrl);
        return "获取成功";
    }


    @GetMapping("/spring-util")
    public String springUtil() {
        /**
         * 证明applicationContext上下文对象, 可以获取到自已注入到容器中Bean
         * PropertiesUtils也经过测试, 获取的使用applicationContext上下文对象获取的Bean为null, 是因为调用工具类的静态方法不会走构造器
         * 导致工具类中的静态变量无法初始化, 默认为空, 可以将静态变量的初始化过程放在, 静态代码块中
         * <p>
         * com.hliushi.learn.web.CURDResource - microServiceUrl:
         * MicroServiceUrl{orderUrl='http://localhost:8002', userUrl='http://localhost:8003', shoppingUrl='http://localhost:8004'}
         */
        ApplicationContext applicationContext = SpringApplicationContextUtils.getApplicationContext();
        MicroServiceUrl microServiceUrl = applicationContext.getBean(MicroServiceUrl.class);
        log.info("microServiceUrl: {}", microServiceUrl);
        return "获取成功";
    }
}
